package org.example.doubleFinger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Sum_of_three_numbers {
    public static void main(String[] args) {
        //三数之和

        //给你一个整数数组 nums ，判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ，同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
        //你返回所有和为 0 且不重复的三元组。
        //注意：答案中不可以包含重复的三元组。
        int[] nums = {-1,0,1,2,-1,-4,-2,-3,3,0,4};
        System.out.print("[ ");
        for (List<Integer> list : threeSum1(nums)) {
            System.out.print("[ ");
            for (Integer i : list) {
                System.out.print(i+" ");
            }
            System.out.print("],");
        }
        System.out.print("],");
    }
    public static List<List<Integer>> threeSum1(int[] nums) {
        //将数组从小到大排序
        nums = sort(nums);
        ArrayList<List<Integer>> arrayList = new ArrayList<>();
        int j ;
        int k ;
        for (int i = 0; i < nums.length; i++) {
            if (i!=0 && nums[i-1]==nums[i]){
                continue;
            }
            j = i+1;
            k = nums.length-1;
            while(j<k){
                int sum = nums[i] + nums[j] + nums[k];
                if (sum == 0){
                    ArrayList<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[k]);
                    arrayList.add(list);
                    j++;
                    k--;
                } else if (sum < 0) {
                    j++;
                }else {
                    k--;
                }
                //去重
                while(j<k && j!=i+1 && nums[j-1]==nums[j]){
                    j++;
                }
                while(j<k && k!= nums.length-1 && nums[k+1]==nums[k]){
                    k--;
                }
            }
        }
        return arrayList;
    }
    public static int[] sort(int[] nums){
        int temp = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length-i-1; j++) {
                if (nums[j] > nums[j+1]){
                    temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
        return nums;
    }
}
